import router from "./router";
import store from "./store";

import { Message, MessageBox } from "element-ui";
import { Dialog, Toast } from "vant";
import axios from "axios";
import NProgress from "nprogress"; // 进度条
import "nprogress/nprogress.css"; // 进度条样式
import { uuid } from "./utils/validate";
import qyType from "./utils/qyForm";

import {
  delTi,
  getAdminToken,
  setAgent,
  getisphoto,
  getisfacetimemkface,
  getisfacetimezxface,
  getisfacetimekjface,
  getisfacetime,
  getwxopenid,
  getapplyid,
  getispay,
  getisfacetimezsface,
  delsubject_id,
  delsubjectTitle,
  delisfacetimezsface,
  delisfacetimemkface,
  delisfacetimezxface,
  delisfacetimekjface,
  delisfacetime,
  setwxstate,
  getuserstate,
  getcurrentInfo,
} from "@/utils/auth"; // 从cookie中获取token
import getPageTitle from "@/utils/get-page-title";
import { maPay, qrcode, PayList } from "@/api/admin";
// import {getUserClassName} from '@/utils/auth'

let http =
  process.env.NODE_ENV === "development"
    ? process.env.VUE_APP_BASE_API
    : window.location.href.slice(0, window.location.href.indexOf("/user"));
let userAgent;

if (
  navigator.userAgent.match(
    /(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone)/i
  )
) {
  setAgent(1);
  userAgent = true;
  document.body.style.minWidth = "auto";
} else {
  setAgent(0);
  userAgent = false;
  document.body.style.minWidth = "1500px";
}
// if(process.env.NODE_ENV === 'development' && userAgent){
//   let scriptB = document.createElement('script')
//   scriptB.id = 'scriptB'
//   scriptB.innerText='eruda.init();'
//   document.head.appendChild(scriptB)
// }else {
//   if(document.getElementById('scriptB')){
//     document.head.removeChild(document.getElementById('scriptB'))
//   }
// }
 // 进度条配置
NProgress.configure({ showSpinner: false });
const MicroMessenger = navigator.userAgent.match(/MicroMessenger/i);
const faceOnce = ['hbdl','ptxh','zghj','xxcj','htaq','senyuan','tzaq','jzaq','htzx'] //只验证一次人脸
if (!userAgent) {
  //手机端登录 使用手机路由拦截器
  // store.dispatch('user/initfunction') //存入企业名称及id
  //initObj
  // document.title = store.state.admin.initObj.alias
  const whiteList = ["/login", "/redirect", "/wxbind"]; // 免登录白名单
  const logTop = ["/login", "/wxbind", "/dashboard", "/face"]; // 免登录白名单
  const examPathList = [
    "/practice/index",
    "/simulation/index",
    "/simulationzs/index",
  ];
 
  // if(!sessionStorage.getItem('Amaintain')){  //将于2022年5月19日20:00至2022年5月20日8:00
  //   let str = ''
  //   if(!qyType('hzdpx')){
  //     str = '为更好的服务广大用户，平台正在进行系统升级维护。在此期间，平台暂停服务，敬请您妥善安排时间。给您带来的不便，敬请谅解，我们将尽快恢复对您的服务！'
  //   }else{
  //     str = '为更好的服务广大用户，平台将于2022年5月19日19:00至2022年5月20日7:00进行系统升级维护。在此期间，平台暂停服务，敬请您妥善安排时间。给您带来的不便，敬请谅解，我们将尽快恢复对您的服务！'
  //   }
  //   MessageBox.alert(str,'平台升级提醒',{
  //     confirmButtonText: '确定',
  //     showClose:false,
  //     callback: action => {
  //       sessionStorage.setItem('Amaintain','维护中')
  //     }
  //   })
  // }
  // alert(navigator.userAgent)
  if (
    http.indexOf("putai") != -1 &&
    Boolean(navigator.userAgent.match(/MicroMessenger/i))
  ) {
    MessageBox.alert(
      "您好，电脑端请用谷歌内核的浏览器或者用手机端打开进行培训考试。",
      "提醒",
      {
        confirmButtonText: "确定",
        showClose: false,
        callback: (action) => {
          window.open(http, "_self");
        },
      }
    );
  } else if (
    http.indexOf("putai") != -1 &&
    !Boolean(navigator.userAgent.match(/(WebKit|Chrome|Firefox)/i))
  ) {
    MessageBox.alert(
      "您好，电脑端请用谷歌内核的浏览器或者用手机端打开进行培训考试。",
      "提醒",
      {
        confirmButtonText: "确定",
        showClose: false,
        callback: (action) => {
          window.close();
        },
      }
    );
  }
  router.beforeEach(async (to, from, next) => {
    let isFace;
    let isPay = {};
    if (getispay()) {
      isPay = JSON.parse(getispay());
    }
    if (getisphoto() && getisphoto() != "undefined") {
      isFace = JSON.parse(getisphoto());
    } else {
      isFace = "";
    }
    store.dispatch("permission/generateRoutes");
    NProgress.start();
    const hasToken = getAdminToken();
    if (Object.keys(store.state.admin.initObj).length == 0) {
      await store.dispatch("user/initfunction"); //初始化企业信息及权限
    }
    let initObj = store.state.admin.initObj;
    if (hasToken) {
      // if(isFace.kjface=='开启'||isFace.mkface=='开启'||isFace.zxface=='开启'||isFace.zsface){

      // }
      // if(to.path=='/login'){
      //   //生成路由
      //   next({ path: '/' })
      //   NProgress.done()

      if (to.path == "/login") {
        //生成路由
        next({ path: "/" });
        NProgress.done();
      } else if (to.path == "/exam" && isFace) {
        //专项练习
        if (
          isFace.mkface != "关闭" &&
          isFace.zxface != "关闭" &&
          !getisfacetime()
        ) {
          // if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia){
          //   next('/face?hasFace=openFaces')
          // }else{
          //   Message.error('该电脑没有摄像头，无法使用该模块')
          //   next('/')
          // }
          await getUserMedia().then((res) => {
            if (res) {
              next("/face?hasFace=openFaces&type=zxface");
            } else {
              Message.error("该电脑没有摄像头，无法使用该模块");
              next("/");
            }
          });
        } else if (isFace.zxface != "关闭" && !getisfacetimezxface()) {
          // if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia){
          //   next('/face?hasFace=zxface')
          // }else{
          //   Message.error('该电脑没有摄像头，无法使用该模块')
          //   next('/')
          // }
          await getUserMedia().then((res) => {
            if (res) {
              next("/face?hasFace=zxface&type=zxface");
            } else {
              Message.error("该电脑没有摄像头，无法使用该模块");
              next("/");
            }
          });
        }
        next();
      } else if (to.path == "/simulationExam" && isFace) {
        if (
          isFace.mkface != "关闭" &&
          isFace.zxface != "关闭" &&
          !getisfacetime()
        ) {
          // if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia){
          //   next('/face?hasFace=openFaces')
          // }else{
          //   Message.error('该电脑没有摄像头，无法使用该模块')
          //   next('/')
          // }
          await getUserMedia().then((res) => {
            if (res) {
              next("/face?hasFace=openFaces&type=mkface");
            } else {
              Message.error("该电脑没有摄像头，无法使用该模块");
              next("/");
            }
          });
        } else if (isFace.mkface != "关闭" && !getisfacetimemkface()) {
          //模拟考试
          // if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia){
          //   next('/face?hasFace=mkface')
          // }else{
          //   Message.error('该电脑没有摄像头，无法使用该模块')
          //   next('/')
          // }
          await getUserMedia().then((res) => {
            if (res) {
              next("/face?hasFace=mkface&type=mkface");
            } else {
              Message.error("该电脑没有摄像头，无法使用该模块");
              next("/");
            }
          });
        }
        next();
      } else if (to.path == "/simulationzsExam" && isFace) {
        //正式考试
        if (isFace.zsface != "关闭" && !getisfacetimezsface()) {
          // if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia){
          //   next('/face?hasFace=zsface')
          // }else{
          //   Message.error('该电脑没有摄像头，无法使用该模块')
          //   next('/')
          // }
          await getUserMedia().then((res) => {
            if (res) {
              next("/face?hasFace=zsface&type=zsface");
            } else {
              Message.error("该电脑没有摄像头，无法使用该模块");
              next("/");
            }
          });
        }
        next();
      } else if (
        to.path == "/curriculum/video" ||
        to.path == "/curriculum/pdf"
      ) {
        //课件视频

        if (
          isFace.kjface&&isFace.kjface != "关闭" &&
          !getisfacetimekjface() && 
          !faceOnce.includes(http.split('//')[1].split('.taijieyun')[0])
        ) {
          //鹤壁电力不校验人脸
          // navigator.mediaDevices && navigator.mediaDevices.getUserMedia
          await getUserMedia().then((res) => {
            if (res) {
              next("/face?hasFace=kjface&type=kjface");
            } else {
              Message.error("该电脑没有摄像头，无法使用该模块");
              next("/");
            }
          });
        }
        next();
        //  if (isFace && isFace.kjface == '开启' && isFace.mkface == '开启' && isFace.zxface == '开启' && !getisfacetime()) {

        //   if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia){
        //     next('/face?hasFace=openFaces')
        //   }else{
        //     Message.error('该电脑没有摄像头，无法使用该模块')
        //     next('/')
        //   }
        // }else if(isFace&&isFace.kjface=='开启'&&!getisfacetimekjface()){

        //   if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia){
        //     next('/face?hasFace=kjface')
        //   }else{
        //     Message.error('该电脑没有摄像头，无法使用该模块')
        //     next('/')
        //   }
        // }
        // next()
      }
      try {
        await store
          .dispatch("user/userInfo")
          .then(() => {
            next();
          })
          .catch(async (err) => {
            Message.error(err.error);
            await store.dispatch("user/resetAdminToken");
            next(`/login`);
          });
      } catch (error) {
        // 删除token并转到登录页面重新登录
        await store.dispatch("user/resetAdminToken");
        next(`/login`);
      }
      if (initObj.wxpay == "是") {
        let plantFormPay = JSON.parse(getcurrentInfo()).need_charge;
        let listObj = [];
        let is_pay = "";
        if (isPay.test_pay && isPay.test_pay == "是") {
          listObj = examPathList;
          is_pay = 1;
        } else {
          listObj = logTop;
          is_pay = isPay.is_pay;
        }
        // next()
        // 删除token并转到登录页面重新登录
        if (listObj.indexOf(to.path) !== -1) {
          next();
        } else {
          if (is_pay == 1) {
            next();
          } else {
            // await store.dispatch('user/resetAdminToken')
            // Message.error('您还没有缴费，请到移动端缴费后再来学习')
            // next(`/login`)
            next("/");
            NProgress.done();
            if (plantFormPay && plantFormPay == 1) {
              MessageBox.confirm(
                "平台名额已到使用上限，请联系管理员开通权限",
                "开通提醒",
                {
                  dangerouslyUseHTMLString: true,
                  showCancelButton: false,
                  closeOnClickModal: false,
                  closeOnPressEscape: false,
                  showClose: false,
                  center: true,
                  beforeClose: (action, instance, done) => {
                    done();
                  },
                }
              );
            } else {
              await maPay({ applyid: getapplyid() }).then((res) => {
                if (res.return_msg == "OK") {
                  qrcode({ str: res.code_url }).then((resA) => {
                    if (resA.code == 200) {
                      MessageBox.confirm(
                        `<img src='${resA.data.url}' />`,
                        "请使用微信扫码缴费",
                        {
                          dangerouslyUseHTMLString: true,
                          center: true,
                          confirmButtonText: "我已缴费",
                          beforeClose: (action, instance, done) => {
                            if (action == "confirm") {
                              PayList({ applyid: getapplyid() }).then(
                                (resB) => {
                                  if (resB.code == 200) {
                                    if (resB.data != "支付成功") {
                                      Message.error(
                                        resB.data + ",请联系管理员"
                                      );
                                    } else {
                                      Message.success("支付成功");
                                      location.reload();
                                      done();
                                    }
                                  } else {
                                    Message.error(resB.msg);
                                  }
                                }
                              );
                            } else {
                              done();
                            }
                          },
                        }
                      );
                      // window.open(resA.data.url)
                    }
                  });
                }
              });
            }
          }
        }

        // else{
        //   if(jflist.indexOf(to.path) !== -1){
        //     next()
        //   }else{
        //     next('/home')
        //     // console.log(uuid(24,32))
        //     Dialog.confirm({
        //       title: '培训提示',
        //       message: '此功能需要购买后才能使用',
        //     }).then(() => {
        //       if(!getwxopenid()){
        //         return Dialog.confirm({
        //           title: '提示',
        //           message: '您还未绑定微信，请点击确定按钮进入账号绑定页面，绑定账号后开通培训权限',
        //           beforeClose:(action, done)=>{
        //             if(action=== 'confirm'){
        //               store.dispatch('user/wxlogin').then(res=>{
        //                 done()
        //                 if(res.code==200){
        //                   window.open(res.data,'_self')
        //                 }
        //               })
        //             }else{
        //               done()
        //             }
        //           }
        //         })
        //       }
        //       let data = {
        //         openid:getwxopenid(),
        //         applyid:getapplyid()
        //       }
        //       store.dispatch('user/wxPayList',data).then(value=>{
        //         if(value.code==200){
        //           let data = JSON.parse(value.data)
        //           let obj = {
        //             "appId":data.appId,
        //             "timeStamp":data.timeStamp,
        //             "nonceStr":data.nonceStr,
        //             "package":data.package,
        //             "signType":data.signType,
        //             "paySign":data.paySign,
        //           }
        //           WeixinJSBridge.invoke(
        //             'getBrandWCPayRequest',obj,
        //             res=>{
        //               if(res.err_msg == "get_brand_wcpay_request:ok" ){
        //                 Toast.success('支付成功');
        //                 location.reload();
        //               }else{
        //                 Toast.fail('支付失败');
        //               }
        //             }
        //           )
        //         }
        //       })

        //       // const fromData={
        //       //   appid:'wx0cc35a917f5b6318',
        //       //   mchid:'1608438123',
        //       //   description:'线上培训权限',
        //       //   out_trade_no:uuid(24,32),
        //       //   notify_url:'https://anhetai.taijieyun.com/index/apply/wxpayNotify',//支付结果通知地址
        //       //   amount:{
        //       //     total:1000,
        //       //   },
        //       //   payer:{
        //       //     openid:getwxopenid()
        //       //   }
        //       // }
        //       // let num = uuid(64,16)
        //       // let obj = 'POST\n/v3/pay/transactions/jsapi\n'+new Date().getTime()+'\n'+num+'\n'+JSON.stringify(fromData)
        //       // console.log(Base64.encode(obj))

        //       //
        //       // axios({
        //       //   url:'/v3/pay/transactions/jsapi',
        //       //   method:'post',
        //       //   headers:{
        //       //     'Content-Type':'application/json',
        //       //     Authorization:'WECHATPAY2-SHA256-RSA2048 mchid=1608438123,nonce_str='+num+',timestamp='+new Date().getTime()+',signature='+Base64.encode(obj)+',serial_no=526F36CCAAF786C6CCE2E45134856E5513A0634F'
        //       //   },
        //       //   data:fromData,
        //       // }).then(res=>{
        //       //   console.log(res,'100')
        //       // })
        //     })
        //     .catch(() => {

        //     });
        //   }
        // }
      }
    } else {
      try {
        if (whiteList.indexOf(to.path) !== -1) {
          next();
        } else {
          next(`/login`);
          NProgress.done();
        }
      } catch (error) {
        alert(error);
      }
    }
    // console.log(initObj.wxpay);

    // console.log(examPathList.indexOf(to.path),'aaa');
    // if (http.indexOf("yzza") != -1 && examPathList.indexOf(to.path) != -1) {
    //   if (logTop.indexOf(to.path) !== -1) {
    //     next();
    //   } else {
    //     if (isPay.test_pay == "是") {
    //       next();
    //     } else {
    //       // await store.dispatch('user/resetAdminToken')
    //       // Message.error('您还没有缴费，请到移动端缴费后再来学习')
    //       // next(`/login`)
    //       next("/");
    //       await maPay({ applyid: getapplyid(), order_type: "练题" }).then(
    //         (res) => {
    //           if (res.return_msg == "OK") {
    //             qrcode({ str: res.code_url }).then((resA) => {
    //               if (resA.code == 200) {
    //                 MessageBox.confirm(
    //                   `<img src='${resA.data.url}' />`,
    //                   "请使用微信扫码缴费",
    //                   {
    //                     dangerouslyUseHTMLString: true,
    //                     center: true,
    //                     confirmButtonText: "我已缴费",
    //                     beforeClose: (action, instance, done) => {
    //                       if (action == "confirm") {
    //                         PayList({
    //                           applyid: getapplyid(),
    //                           order_type: "练题",
    //                         }).then((resB) => {
    //                           if (resB.code == 200) {
    //                             if (resB.data != "支付成功") {
    //                               Message.error(resB.data + ",请联系管理员");
    //                             } else {
    //                               Message.success("支付成功");
    //                               location.reload();
    //                               done();
    //                             }
    //                           } else {
    //                             Message.error(resB.msg);
    //                           }
    //                         });
    //                       } else {
    //                         done();
    //                       }
    //                     },
    //                   }
    //                 );
    //                 // window.open(resA.data.url)
    //               }
    //             });
    //           }
    //         }
    //       );
    //     }
    //   }
    // } else {
    // }
  });
} else {
  const whiteList = ["/wxbind", "/loading", "/wxlogin"]; // 免hasToken白名单
  const jflist = [
    "/wxbind",
    "/loading",
    "/wxlogin",
    "/home",
    "/",
    "/404",
    "/face",
  ]; //未缴费情况下可使用的路由

  const examPathList = ["/practice"];

  // if(!sessionStorage.getItem('Amodelmaintain')){

  //   if(!qyType('hzdpx')){
  //     str = '为更好的服务广大用户，平台正在进行系统升级维护。在此期间，平台暂停服务，敬请您妥善安排时间。给您带来的不便，敬请谅解，我们将尽快恢复对您的服务！','平台升级提醒'
  //   }else{
  //     str = '为更好的服务广大用户，平台将于2022年5月19日19:00至2022年5月20日7:00进行系统升级维护。在此期间，平台暂停服务，敬请您妥善安排时间。给您带来的不便，敬请谅解，我们将尽快恢复对您的服务！','平台升级提醒'
  //   }

  // }
  // if(http.indexOf('donggang')!=-1){
  //   store.dispatch('user/resetAdminToken')
  // }

  if (
    getisfacetimezsface() &&
    getapplyid() != JSON.parse(getisfacetimezsface()).applyid
  ) {
    delisfacetimezsface();
  }
  if (
    getisfacetimemkface() &&
    getapplyid() != JSON.parse(getisfacetimemkface()).applyid
  ) {
    delisfacetimemkface();
  }
  if (
    getisfacetimezxface() &&
    getapplyid() != JSON.parse(getisfacetimezxface()).applyid
  ) {
    delisfacetimezxface();
  }
  if (
    getisfacetimekjface() &&
    getapplyid() != JSON.parse(getisfacetimekjface()).applyid
  ) {
    delisfacetimekjface();
  }
  if (getisfacetime() && getapplyid() != JSON.parse(getisfacetime()).applyid) {
    delisfacetime();
  }
  delTi();
  // &&window.location.href.includes("tjy")
  // if(!window.location.href.includes("/practice")){
  //   store.dispatch('user/resetSeccson')
  // }
  //每次进入  清除所有储存记录
  router.beforeEach(async (to, from, next) => {
    let isFace;
    let isPay = {};

    if (getispay()) {
      isPay = JSON.parse(getispay());
    }
    if (getisphoto() && getisphoto() != "undefined") {
      isFace = JSON.parse(getisphoto());
    } else {
      isFace = "";
    }
    const hasToken = getAdminToken();
    store.dispatch("permission/generateRoutes");
    if (Object.keys(store.state.admin.initObj).length == 0) {
      await store.dispatch("user/initfunction"); //初始化企业信息及权限
    }
    let initObj = store.state.admin.initObj;

    if (hasToken) {
      if (to.path == "/loading") {
        next(`/home`);
      } else if (to.path == "/exam") {
        if (to.query.titleName == "模拟考试" && isFace) {
          if (
            isFace.kjface != "关闭" &&
            isFace.mkface != "关闭" &&
            isFace.zxface != "关闭" &&
            !getisfacetime()
          ) {
            next("/face?hasFace=openFaces&type=mkface");
          } else if (isFace.mkface != "关闭" && !getisfacetimemkface()) {
            next("/face?hasFace=mkface&type=mkface");
          }
          next();
        }
        if (
          (!to.query.titleName || to.query.titleName == "专项练习") &&
          isFace
        ) {
          if (
            isFace.kjface != "关闭" &&
            isFace.mkface != "关闭" &&
            isFace.zxface != "关闭" &&
            !getisfacetime()
          ) {
            next("/face?hasFace=openFaces&type=zxface");
          } else if (isFace.zxface != "关闭" && !getisfacetimezxface()) {
            next("/face?hasFace=zxface&type=zxface");
          }
          next();
        }
        if (
          to.query.titleName == "正式考试" &&
          isFace &&
          isFace.zsface != "关闭" &&
          !getisfacetimezsface() &&
          from.name != "result"
        ) {
          next("/face?hasFace=zsface&type=zsface");
        }
        next();
      } else if (to.path == "/video" || to.path == "/PDF") {
        // if(isFace&&isFace.kjface=='开启'&&!getisfacetime()){
        //   next('/face?hasFace=openFaces')
        // } else
        //&&!process.env.NODE_ENV === 'development'
        // &&!http.includes('tjy')
        if (!MicroMessenger &&!http.includes('tjy')) {
          if (to.path == "/video") {
            Dialog.confirm({
              title: "提示",
              message: "此功能需要在微信App中打开才能使用",
            })
              .then(() => {
                next("/study");
              })
              .catch(() => {
                next("/study");
              });
            return;
          }
        }
        if (
          isFace &&
          isFace.kjface != "关闭" &&
          !getisfacetimekjface() &&
          !faceOnce.includes(http.split('//')[1].split('.taijieyun')[0])
        ) {
          //鹤壁电力不验证人脸信息
          next("/face?hasFace=kjface&type=kjface");
        }
        next();
      }

      try {
        await store
          .dispatch("user/userInfo")
          .then(() => {
            next();
          })
          .catch(async (err) => {
            Message.error(err.error);
            await store.dispatch("user/resetAdminToken");
            next(`/login`);
          });
      } catch (error) {
        // 删除token并转到登录页面重新登录
        await store.dispatch("user/resetAdminToken");
        next(`/login`);
      }
      // next()
    } else {
      if (whiteList.indexOf(to.path) !== -1) {
        next();
      } else {
        next(`/loading`);
      }
    }
    if (initObj.wxpay == "是") {
      let plantFormPay = JSON.parse(getcurrentInfo()).need_charge;
      let listObj = [];
      let is_pay = "";
      if (isPay.test_pay && isPay.test_pay == "是") {
        listObj = examPathList;
        is_pay = 1;
      } else {
        listObj = jflist;
        is_pay = isPay.is_pay;
      }
      if (listObj.indexOf(to.path) !== -1) {
        next();
      } else {
        if (is_pay == 1) {
          next();
        } else {
          next("/home");
          // console.log(uuid(24,32))
          if (plantFormPay && plantFormPay == 1) {
            Dialog.confirm({
              title: "开通提醒",
              message: "平台名额已到使用上限，请联系管理员开通权限。",
            })
              .then(() => {})
              .catch(() => {});
          } else {
            Dialog.confirm({
              title: "培训提示",
              message: "此功能需要购买后才能使用",
            })
              .then(() => {
                if (!getwxopenid()) {
                  return Dialog.confirm({
                    title: "提示",
                    message:
                      "您还未绑定微信，请点击确定按钮进入账号绑定页面，绑定账号后开通培训权限",
                    beforeClose: (action, done) => {
                      if (action === "confirm") {
                        // store.dispatch('user/wxlogin').then(res=>{
                        //   done()
                        //   if(res.code==200){
                        //     window.open(res.data,'_self')
                        //   }
                        // })
                        store.dispatch("user/getcode").then((res) => {
                          done();
                          if (res.code == 200) {
                            setwxstate(res.data.state);
                            window.open(res.data.url, "_self");
                          }
                        });
                      } else {
                        done();
                      }
                    },
                  });
                }
                let data = {
                  openid: getwxopenid(),
                  applyid: getapplyid(),
                };
                if (http.indexOf("anhetai") != -1) {
                  store.dispatch("user/wxPayList", data).then((value) => {
                    if (value.code == 200) {
                      let data = JSON.parse(value.data);
                      let obj = {
                        appId: data.appId,
                        timeStamp: data.timeStamp,
                        nonceStr: data.nonceStr,
                        package: data.package,
                        signType: data.signType,
                        paySign: data.paySign,
                      };
                      WeixinJSBridge.invoke(
                        "getBrandWCPayRequest",
                        obj,
                        (res) => {
                          if (res.err_msg == "get_brand_wcpay_request:ok") {
                            Toast.success("支付成功");
                            location.reload();
                          } else {
                            Toast.fail("支付失败");
                          }
                        }
                      );
                    }
                  });
                } else {
                  store.dispatch("user/wxPayListUp", data).then((value) => {
                    if (value.code == 200) {
                      let data = value.data;
                      let obj = {
                        appId: data.appId,
                        timeStamp: data.timeStamp,
                        nonceStr: data.nonceStr,
                        package: data.package,
                        signType: data.signType,
                        paySign: data.paySign,
                      };
                      WeixinJSBridge.invoke(
                        "getBrandWCPayRequest",
                        obj,
                        (res) => {
                          if (res.err_msg == "get_brand_wcpay_request:ok") {
                            Toast.success("支付成功");
                            location.reload();
                          } else {
                            Toast.fail("支付失败");
                          }
                        }
                      );
                    }
                  });
                }

                // const fromData={
                //   appid:'wx0cc35a917f5b6318',
                //   mchid:'1608438123',
                //   description:'线上培训权限',
                //   out_trade_no:uuid(24,32),
                //   notify_url:'https://anhetai.taijieyun.com/index/apply/wxpayNotify',//支付结果通知地址
                //   amount:{
                //     total:1000,
                //   },
                //   payer:{
                //     openid:getwxopenid()
                //   }
                // }
                // let num = uuid(64,16)
                // let obj = 'POST\n/v3/pay/transactions/jsapi\n'+new Date().getTime()+'\n'+num+'\n'+JSON.stringify(fromData)
                // console.log(Base64.encode(obj))

                //
                // axios({
                //   url:'/v3/pay/transactions/jsapi',
                //   method:'post',
                //   headers:{
                //     'Content-Type':'application/json',
                //     Authorization:'WECHATPAY2-SHA256-RSA2048 mchid=1608438123,nonce_str='+num+',timestamp='+new Date().getTime()+',signature='+Base64.encode(obj)+',serial_no=526F36CCAAF786C6CCE2E45134856E5513A0634F'
                //   },
                //   data:fromData,
                // }).then(res=>{
                //   console.log(res,'100')
                // })
              })
              .catch(() => {});
          }
        }
      }
    } else {
      next();
    }

    // if (http.indexOf("yzza") != -1 && examPathList.indexOf(to.path) != -1) {
    //   if (jflist.indexOf(to.path) !== -1) {
    //     next();
    //   } else {
    //     if (isPay.test_pay == "是") {
    //       next();
    //     } else {
    //       next("/home");
    //       // console.log(uuid(24,32))
    //       Dialog.confirm({
    //         title: "培训提示",
    //         message: "此功能需要购买后才能使用",
    //       })
    //         .then(() => {
    //           if (!getwxopenid()) {
    //             return Dialog.confirm({
    //               title: "提示",
    //               message:
    //                 "您还未绑定微信，请点击确定按钮进入账号绑定页面，绑定账号后开通培训权限",
    //               beforeClose: (action, done) => {
    //                 if (action === "confirm") {
    //                   next();
    //                   store.dispatch("user/getcode").then((res) => {
    //                     done();
    //                     if (res.code == 200) {
    //                       setwxstate(res.data.state);
    //                       window.open(res.data.url, "_self");
    //                     }
    //                   });
    //                 } else {
    //                   done();
    //                 }
    //               },
    //             });
    //           }
    //           let data = {
    //             openid: getwxopenid(),
    //             applyid: getapplyid(),
    //             order_type: "练题",
    //           };
    //           store.dispatch("user/wxPayListUp", data).then((value) => {
    //             if (value.code == 200) {
    //               let data = value.data;
    //               let obj = {
    //                 appId: data.appId,
    //                 timeStamp: data.timeStamp,
    //                 nonceStr: data.nonceStr,
    //                 package: data.package,
    //                 signType: data.signType,
    //                 paySign: data.paySign,
    //               };
    //               WeixinJSBridge.invoke("getBrandWCPayRequest", obj, (res) => {
    //                 if (res.err_msg == "get_brand_wcpay_request:ok") {
    //                   Toast.success("支付成功");
    //                   location.reload();
    //                 } else {
    //                   Toast.fail("支付失败");
    //                 }
    //               });
    //             }
    //           });

    //           // const fromData={
    //           //   appid:'wx0cc35a917f5b6318',
    //           //   mchid:'1608438123',
    //           //   description:'线上培训权限',
    //           //   out_trade_no:uuid(24,32),
    //           //   notify_url:'https://anhetai.taijieyun.com/index/apply/wxpayNotify',//支付结果通知地址
    //           //   amount:{
    //           //     total:1000,
    //           //   },
    //           //   payer:{
    //           //     openid:getwxopenid()
    //           //   }
    //           // }
    //           // let num = uuid(64,16)
    //           // let obj = 'POST\n/v3/pay/transactions/jsapi\n'+new Date().getTime()+'\n'+num+'\n'+JSON.stringify(fromData)
    //           // console.log(Base64.encode(obj))

    //           //
    //           // axios({
    //           //   url:'/v3/pay/transactions/jsapi',
    //           //   method:'post',
    //           //   headers:{
    //           //     'Content-Type':'application/json',
    //           //     Authorization:'WECHATPAY2-SHA256-RSA2048 mchid=1608438123,nonce_str='+num+',timestamp='+new Date().getTime()+',signature='+Base64.encode(obj)+',serial_no=526F36CCAAF786C6CCE2E45134856E5513A0634F'
    //           //   },
    //           //   data:fromData,
    //           // }).then(res=>{
    //           //   console.log(res,'100')
    //           // })
    //         })
    //         .catch(() => {});
    //     }
    //   }
    // }
    // if(MicroMessenger=='micromessenger'||MicroMessenger=='MicroMessenger'){

    // }else{
    //   next()
    // }
  });
}
router.afterEach(() => {
  // 进度条结束
  NProgress.done();
});

// window.onbeforeunload = function (e) {
//   var n = window.event.screenX - window.screenLeft;
//   var b = n > document.documentElement.scrollWidth-20;
//   if(b && window.event.clientY < 0 || window.event.altKey)
//     {
//     // 清除
//     delsubjectTitle()
//     delapplyid()
//     delsubject_id()
//     }
// };
export async function getUserMedia(constraints, success, error) {
  var isyes = true;
  try {
    if (navigator.mediaDevices.getUserMedia) {
      return new Promise(async (resolve) => {
        //最新的标准API
        await navigator.mediaDevices
          .getUserMedia({ video: { width: 480, height: 320 } })
          .then(() => {
            resolve(true);
          })
          .catch((res) => {
            resolve(false);
          });
      });
    } else if (navigator.webkitGetUserMedia) {
      //webkit核心浏览器
      await new Promise((resolve) => {
        navigator.webkitGetUserMedia(
          { video: { width: 480, height: 320 } },
          () => {
            resolve(true);
          },
          () => {
            resolve(false);
          }
        );
      });
      // return isyes
    } else if (navigator.mozGetUserMedia) {
      //firfox浏览器
      console.log(123);
      await new Promise((resolve) => {
        navigator.mozGetUserMedia(
          { video: { width: 480, height: 320 } },
          () => {
            resolve(true);
          },
          () => {
            resolve(false);
          }
        );
      });
    } else if (navigator.getUserMedia) {
      //旧版API
      await new Promise((resolve) => {
        navigator.getUserMedia(
          { video: { width: 480, height: 320 } },
          () => {
            resolve(true);
          },
          () => {
            resolve(false);
          }
        );
      });
      // return true
    } else {
      await new Promise((resolve) => {
        resolve(false);
      });
    }
  } catch {
    return new Promise((resolve) => {
      resolve(false);
    });
  }
}
